package com.wHitE.dao.impl;

import com.wHitE.dao.RegisterDao;

import java.sql.*;

public class RegisterDaoImpl implements RegisterDao {
    private String msg;

    @Override
    public String userRegister(String username, String email, String password) {
        try {
            // 连接（JDBC）数据库并将数据写入数据库（MySQL）中
            // 1.加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.连接数据库
            Connection connection = DriverManager.getConnection("jdbc:mysql:" +
                    "//localhost:3306/javaweb_database", "root", "123456");

            // 2.1 先判断用户名是否已存在
            String preSql = "select * from user where username=?";
            // 2.2 预处理
            PreparedStatement prePst = connection.prepareStatement(preSql);
            prePst.setString(1, username);
            // 2.3执行并接受结果
            ResultSet resultSet = prePst.executeQuery();
            while (resultSet.next()) {
                if (resultSet.getString("password") != null && resultSet.getString("password") != "") {
                    prePst.close();
                    // 断开连接
                    connection.close();
                    return "注册失败!用户名已存在";
                }
            }
            // 3.发送SQL语句
            String sql = "insert into user(username,password,email) values(?,?,?)";
            // 预处理
            PreparedStatement pst = connection.prepareStatement(sql);
            pst.setString(1, username);
            pst.setString(2, password);
            pst.setString(3, email);
            // 执行并接收结果
            msg = "注册失败!出现错误";
            if (pst.executeUpdate() > 0) {
                msg = "success";
            }
            pst.close();
            // 断开连接
            connection.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return msg;
    }
}
